package com.wb.adutils.ads.gmad

import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import com.bytedance.msdk.api.AdError
import com.bytedance.msdk.api.v2.GMAdConstant
import com.bytedance.msdk.api.v2.GMDislikeCallback
import com.bytedance.msdk.api.v2.ad.nativeAd.GMNativeAd
import com.bytedance.msdk.api.v2.ad.nativeAd.GMNativeAdLoadCallback
import com.bytedance.msdk.api.v2.ad.nativeAd.GMNativeExpressAdListener
import com.bytedance.msdk.api.v2.ad.nativeAd.GMUnifiedNativeAd
import com.bytedance.msdk.api.v2.slot.GMAdSlotNative
import com.bytedance.msdk.api.v2.slot.paltform.GMAdSlotGDTOption
import com.wb.adutils.AdBaseLoader
import com.wb.adutils.db.AdEntity
import com.wb.adutils.tools.AdConstants
import com.wb.adutils.tools.LogC
import java.lang.Exception


class GMNativeAdUtils(val adEntity: AdEntity?): AdBaseLoader(adEntity) {

    private var gmaNativeAdList: ArrayList<GMNativeAd>? = null

    override fun excLoadAd(activity: Activity) {
        //模板视频
       try {
           if (isAdLoadSuccess && gmaNativeAdList?.isNotEmpty() == true) {
               listener?.onAdLoaded(gmaNativeAdList)
               return
           }

           val mTTAdNative = GMUnifiedNativeAd(activity, adEntity?.adUnit)
           val gdtConfig = GMAdSlotGDTOption.Builder()
               .setGDTAutoPlayMuted(true) //自动播放是否静音，默认true
               .setGDTDetailPageMuted(true) //详情页是否静音，默认值为false，即有声播放；
               .setGDTEnableDetailPage(true) //是否能跳转详情页，默认true
               .setGDTEnableUserControl(false) //是否能控制是否暂停与播放，默认false
               .setAutoPlayPolicy(GMAdSlotGDTOption.AutoPlayPolicy.ALWAYS) //自动播放策略--
               .setDownAPPConfirmPolicy(GMAdSlotGDTOption.DownAPPConfirmPolicy.TYPE_DEFAULT) //指定点击 APP 广告后是否展示二次确认，可选项包括 Default（wifi 不展示，非wifi 展示），NoConfirm（所有情况不展示）
               .build()

           val adSlotNative = GMAdSlotNative.Builder()
               .setGMAdSlotGDTOption(gdtConfig) //gdt相关的配置
               .setAdStyleType(GMAdConstant.TYPE_EXPRESS_AD) //表示请求的模板广告还是原生广告，com.bytedance.msdk.api.AdSlot.TYPE_EXPRESS_AD：模板广告 ； com.bytedance.msdk.api.AdSlot.TYPE_NATIVE_AD：原生广告
               .setAdCount(count) //请求广告数量为1到3条
               .setImageAdSize(width, height)
               .setVolume(0f)
               .setBidNotify(true)
               .setMuted(true)
               .build()

           mTTAdNative.loadAd(adSlotNative, object : GMNativeAdLoadCallback {
               override fun onAdLoaded(ads: List<GMNativeAd>) {
                   if (timeoutDisposable?.isDisposed == true) { // 已超时
                       LogC.e("信息流广告 -> onAdLoaded...但已超时...")
                       return
                   }
                   LogC.e("信息流广告 -> onAdLoaded..." + ads.size)
                   timeoutDisposable?.dispose()
                   isAdLoadSuccess = true
                   gmaNativeAdList?.clear()
                   gmaNativeAdList = ArrayList(ads)
                   if (gmaNativeAdList.isNullOrEmpty()) {
                       listener?.onAdLoadFail(AdConstants.AD_ERROR_CODE_INTERNAL)
                       release()
                   } else {
                       listener?.onAdLoaded(ads)
                   }
               }

               override fun onAdLoadedFail(p0: AdError) {
                   LogC.e("信息流广告 -> onAdLoadedFail...code=${p0.code}, msg=${p0.message}")
                   excAdLoadFail(p0.code)
               }
           })
           LogC.e("信息流广告 -> 准备开始加载广告...")
       } catch (e: Exception) {
           e.printStackTrace()
           timeoutDisposable?.dispose()
           listener?.onAdLoadFail(AdConstants.AD_ERROR_CODE_EXCEPTION)
           release()
       }
    }

    override fun onResume() {
        gmaNativeAdList?.forEach {
            it.resume()
        }
    }

    override fun onPause() {
        gmaNativeAdList?.forEach {
            it.onPause()
        }
    }

    override fun showAd(adRoot: ViewGroup?) {
        LogC.e("信息流广告 -> showAd...")
        val activity = findActivity(adRoot?.context)
        if (adRoot == null || activity == null || activity.isDestroyed || activity.isFinishing) {
            release()
            return
        }
        if (gmaNativeAdList.isNullOrEmpty()) {
            listener?.onAdLoadFail(AdConstants.AD_ERROR_CODE_NOT_LOAD_SUCCESS)
            release()
            return
        }
        val nativeAd = gmaNativeAdList?.first()
        nativeAd?.setNativeAdListener(object : GMNativeExpressAdListener {
            override fun onAdClick() {
                LogC.e("信息流广告 -> showAd...onAdClick...")
                listener?.onAdClicked()
            }

            override fun onAdShow() {
                LogC.e("信息流广告 -> showAd...onAdShow...")
                listener?.onAdDisplay()
            }

            override fun onRenderFail(p0: View?, p1: String?, p2: Int) {
                LogC.e("信息流广告 -> showAd...onRenderFail...$p1, $p2")
                listener?.onAdLoadFail(p2)
                release()
            }

            override fun onRenderSuccess(p0: Float, p1: Float) {
                LogC.e("信息流广告 -> showAd...onRenderSuccess...$p0 x $p1")
                adRoot.removeAllViews()
                adRoot.visibility = View.VISIBLE
                val layoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
                layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT)
                adRoot.addView(nativeAd.expressView, layoutParams)
            }

        })

        //使用默认模板中默认dislike弹出样式
        nativeAd?.setDislikeCallback(activity, object : GMDislikeCallback {
            override fun onShow() {}
            override fun onSelected(value: Int, enforce: String?) {
                LogC.e("信息流广告 -> Dislike -> onSelected...value=$value, enforce=$enforce")
            }

            override fun onCancel() { // 无法关闭
                LogC.e("信息流广告 -> Dislike -> onCancel...")
                listener?.onAdLoadFail(AdConstants.AD_ERROR_CODE_USER_CANCEL)
                release()
            }
            override fun onRefuse() {
                LogC.e("信息流广告 -> Dislike -> onRefuse...")
            }
        })
        // 渲染广告
        nativeAd?.render()
    }


    override fun release() {
        super.release()
        gmaNativeAdList?.forEach {
            it.destroy()
        }
        gmaNativeAdList?.clear()
        gmaNativeAdList = null
    }


}